<template>
  <div class="teacher-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>教师管理</h1>
      <el-button 
        type="primary" 
        @click="openCreateDialog"
        class="create-btn"
      >
        <el-icon><Plus /></el-icon>
        创建教师账号
      </el-button>
    </div>

    <!-- 筛选区域 -->
    <el-card class="filter-card">
      <div class="filter-container">
        <el-input 
          v-model="filterForm.name" 
          placeholder="输入教师姓名" 
          prefix-icon="Search"
          class="name-filter"
          @keyup.enter="fetchTeachers"
        />
        <el-select 
          v-model="filterForm.classId" 
          placeholder="选择负责班级" 
          class="class-filter"
          @change="fetchTeachers"
        >
          <el-option 
            value="" 
            label="全部班级"
          />
          <el-option 
            v-for="cls in classes" 
            :key="cls.id" 
            :value="cls.id"
            :label="`${cls.grade}年级${cls.name}`"
          />
        </el-select>
        <el-button 
          type="primary" 
          @click="fetchTeachers"
        >
          查询
        </el-button>
        <el-button 
          @click="resetFilter"
        >
          重置
        </el-button>
      </div>
    </el-card>

    <!-- 教师列表 -->
    <el-card class="teacher-list-card">
      <el-table 
        :data="teachers" 
        border 
        stripe
        :loading="tableLoading"
      >
        <el-table-column 
          prop="teacher_name" 
          label="教师姓名" 
          width="180"
        />
        <el-table-column 
          prop="position" 
          label="职位" 
          width="180"
        />
        <el-table-column 
          prop="class_role" 
          label="班级角色" 
          width="180"
        />
        <el-table-column 
          label="操作" 
          width="400"
        >
          <template #default="scope">
            <el-button 
              type="text" 
              @click="showPassword(scope.row.teacher_password)"
            >
              查看口令
            </el-button>
            <el-button 
              type="text" 
              @click="openEditDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              type="text" 
              @click="openSetHeadTeacherDialog(scope.row)"
            >
              设定班主任
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建教师对话框 -->
    <el-dialog 
      v-model="createDialogVisible" 
      title="创建教师账号" 
      :close-on-click-modal="false"
    >
      <el-form 
        :model="createForm" 
        :rules="createRules" 
        ref="createFormRef" 
        label-width="120px"
      >
        <el-form-item label="教师姓名" prop="name">
          <el-input 
            v-model="createForm.name" 
            placeholder="请输入教师姓名"
          />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input 
            v-model="createForm.position" 
            placeholder="请输入教师职位"
          />
        </el-form-item>
        <el-form-item label="管理员口令" prop="adminPassword">
          <el-input 
            v-model="createForm.adminPassword" 
            type="password" 
            placeholder="请输入管理员口令"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleCreateTeacher"
          :loading="createLoading"
        >
          创建
        </el-button>
      </template>
    </el-dialog>

    <!-- 口令显示对话框 -->
    <el-dialog 
      v-model="passwordDialogVisible" 
      title="教师口令" 
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="password-content">
        <div class="password-hash">{{ currentPassword }}</div>
        <p class="password-desc">
          教师口令用于注册教师账号与教师权限重要操作，请妥善提供给教师。
        </p>
      </div>
      <template #footer>
        <el-button 
          type="primary" 
          @click="passwordDialogVisible = false"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑教师对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑教师信息" 
      :close-on-click-modal="false"
    >
      <el-form 
        :model="editForm" 
        :rules="editRules" 
        ref="editFormRef" 
        label-width="140px"
      >
        <el-form-item label="教师姓名" prop="name">
          <el-input 
            v-model="editForm.name" 
            placeholder="请输入教师姓名"
          />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input 
            v-model="editForm.position" 
            placeholder="请输入教师职位"
          />
        </el-form-item>
        <el-form-item label="教师口令（可选）" prop="teacherPassword">
          <el-input 
            v-model="editForm.teacherPassword" 
            type="password" 
            placeholder="不修改请留空"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="管理员口令" prop="adminPassword">
          <el-input 
            v-model="editForm.adminPassword" 
            type="password" 
            placeholder="请输入管理员口令"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleEditTeacher"
          :loading="editLoading"
        >
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 设定班主任对话框 -->
    <el-dialog 
      v-model="setHeadTeacherDialogVisible" 
      title="设定班主任班级" 
      :close-on-click-modal="false"
    >
      <el-form 
        :model="headTeacherForm" 
        :rules="headTeacherRules" 
        ref="headTeacherFormRef" 
        label-width="120px"
      >
        <el-form-item label="选择班级" prop="classId">
          <el-radio-group v-model="headTeacherForm.classId">
            <el-radio 
              v-for="cls in classes" 
              :key="cls.id" 
              :label="cls.id"
            >
              {{ `${cls.grade}年级${cls.name}` }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="管理员口令" prop="adminPassword">
          <el-input 
            v-model="headTeacherForm.adminPassword" 
            type="password" 
            placeholder="请输入管理员口令"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="setHeadTeacherDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSetHeadTeacher"
          :loading="setHeadTeacherLoading"
        >
          设定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElForm } from 'element-plus';
import { 
  listTeachers, 
  editTeacher,
  type TeacherItem
} from '../../api/teachermgr';
import { createTeacher } from "../../api/register"
import { 
  listClasses, 
  setHeadTeacher,
  type ClassItem
} from '../../api/classmgr';
import { Plus } from '@element-plus/icons-vue';

// 状态管理
const classes = ref<ClassItem[]>([]);
const teachers = ref<TeacherItem[]>([]);
const tableLoading = ref(false);
const classLoading = ref(false);

// 筛选表单
const filterForm = reactive({
  name: '',
  classId: ''
});

// 创建教师相关
const createDialogVisible = ref(false);
const createLoading = ref(false);
const createFormRef = ref<InstanceType<typeof ElForm>>();
const createForm = reactive({
  name: '',
  position: '',
  adminPassword: ''
});
const createRules = {
  name: [{ required: true, message: '请输入教师姓名', trigger: 'blur' }],
  position: [{ required: true, message: '请输入教师职位', trigger: 'blur' }],
  adminPassword: [{ required: true, message: '请输入管理员口令', trigger: 'blur' }]
};

// 口令显示相关
const passwordDialogVisible = ref(false);
const currentPassword = ref('');

// 编辑教师相关
const editDialogVisible = ref(false);
const editLoading = ref(false);
const editFormRef = ref<InstanceType<typeof ElForm>>();
const editForm = reactive({
  userId: 0,
  teacherId: 0,
  name: '',
  position: '',
  teacherPassword: '',
  adminPassword: ''
});
const editRules = {
  name: [{ required: true, message: '请输入教师姓名', trigger: 'blur' }],
  position: [{ required: true, message: '请输入教师职位', trigger: 'blur' }],
  adminPassword: [{ required: true, message: '请输入管理员口令', trigger: 'blur' }]
};

// 设定班主任相关
const setHeadTeacherDialogVisible = ref(false);
const setHeadTeacherLoading = ref(false);
const headTeacherFormRef = ref<InstanceType<typeof ElForm>>();
const headTeacherForm = reactive({
  classId: 0,
  teacherId: 0,
  adminPassword: ''
});
const headTeacherRules = {
  classId: [{ required: true, message: '请选择班级', trigger: 'change' }],
  adminPassword: [{ required: true, message: '请输入管理员口令', trigger: 'blur' }]
};

// 页面加载时获取数据
onMounted(async () => {
  await fetchClasses();
  await fetchTeachers();
});

// 获取未毕业班级列表
const fetchClasses = async () => {
  try {
    classLoading.value = true;
    const res = await listClasses();
    if (res.code === 200) {
      classes.value = res.content;
    } else {
      ElMessage.error(res.msg || '获取班级列表失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取班级列表异常');
  } finally {
    classLoading.value = false;
  }
};

// 获取教师列表
const fetchTeachers = async () => {
  try {
    tableLoading.value = true;
    const res = await listTeachers({
      class_id: filterForm.classId ? Number(filterForm.classId) : undefined,
      name: filterForm.name || undefined
    });
    if (res.code === 200) {
      teachers.value = res.content;
    } else {
      ElMessage.error(res.msg || '获取教师列表失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取教师列表异常');
  } finally {
    tableLoading.value = false;
  }
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.name = '';
  filterForm.classId = '';
  fetchTeachers();
};

// 打开创建教师对话框
const openCreateDialog = () => {
  createForm.name = '';
  createForm.position = '';
  createForm.adminPassword = '';
  createDialogVisible.value = true;
};

// 处理创建教师
const handleCreateTeacher = async () => {
  if (!createFormRef.value) return;
  
  try {
    createLoading.value = true;
    await createFormRef.value.validate();
    
    const res = await createTeacher({
      name: createForm.name,
      position: createForm.position,
      admin_password: createForm.adminPassword
    });
    
    if (res.code === 200) {
      createDialogVisible.value = false;
      // 显示口令对话框
      currentPassword.value = res.content.password_hash;
      passwordDialogVisible.value = true;
      // 刷新教师列表
      fetchTeachers();
      ElMessage.success('教师账号创建成功');
    } else {
      ElMessage.error(res.msg || '创建教师账号失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '创建教师账号异常');
  } finally {
    createLoading.value = false;
  }
};

// 显示教师口令
const showPassword = (password: string) => {
  currentPassword.value = password;
  passwordDialogVisible.value = true;
};

// 打开编辑教师对话框
const openEditDialog = (teacher: TeacherItem) => {
  editForm.userId = teacher.user_id;
  editForm.teacherId = teacher.teacher_id;
  editForm.name = teacher.teacher_name;
  editForm.position = teacher.position;
  editForm.teacherPassword = '';
  editForm.adminPassword = '';
  editDialogVisible.value = true;
};

// 处理编辑教师
const handleEditTeacher = async () => {
  if (!editFormRef.value) return;
  
  try {
    editLoading.value = true;
    await editFormRef.value.validate();
    
    const res = await editTeacher({
      user_id: editForm.userId,
      teacher_id: editForm.teacherId,
      name: editForm.name,
      position: editForm.position,
      teacher_password: editForm.teacherPassword || undefined,
      admin_password: editForm.adminPassword
    });
    
    if (res.code === 200) {
      editDialogVisible.value = false;
      fetchTeachers();
      ElMessage.success('教师信息编辑成功');
    } else {
      ElMessage.error(res.msg || '编辑教师信息失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '编辑教师信息异常');
  } finally {
    editLoading.value = false;
  }
};

// 打开设定班主任对话框
const openSetHeadTeacherDialog = (teacher: TeacherItem) => {
  headTeacherForm.teacherId = teacher.teacher_id;
  headTeacherForm.classId = 0;
  headTeacherForm.adminPassword = '';
  setHeadTeacherDialogVisible.value = true;
};

// 处理设定班主任
const handleSetHeadTeacher = async () => {
  if (!headTeacherFormRef.value) return;
  
  try {
    setHeadTeacherLoading.value = true;
    await headTeacherFormRef.value.validate();
    
    const res = await setHeadTeacher({
      class_id: headTeacherForm.classId,
      teacher_id: headTeacherForm.teacherId,
      admin_password: headTeacherForm.adminPassword
    });
    
    if (res.code === 200) {
      setHeadTeacherDialogVisible.value = false;
      fetchTeachers();
      ElMessage.success('班主任设定成功');
    } else {
      ElMessage.error(res.msg || '设定班主任失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '设定班主任异常');
  } finally {
    setHeadTeacherLoading.value = false;
  }
};
</script>

<style scoped>
.teacher-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 20px;
  color: var(--el-text-color-primary);
}

.create-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.filter-card {
  margin-bottom: 20px;
  background-color: #f0f2f5;
}

.filter-container {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.name-filter {
  width: 250px;
}

.class-filter {
  width: 200px;
}

.teacher-list-card {
  min-height: 400px;
  background-color: #f0f2f5;
}

.password-content {
  text-align: center;
  padding: 20px 0;
}

.password-hash {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 15px;
  letter-spacing: 2px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.password-desc {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  margin: 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .filter-container {
    flex-direction: column;
  }
  
  .name-filter, .class-filter {
    width: 100%;
  }
}
</style>